package com.neuedu.service.impl;

import com.neuedu.entity.Food;
import com.neuedu.entity.Meal;
import com.neuedu.mapper.MealMapper;
import com.neuedu.service.MealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.vo.MealVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * <p>
 * 膳食日历表 服务实现类
 * </p>
 *
 * @author wangyu
 * @since 2025-10-21
 */
@Service
public class MealServiceImpl extends ServiceImpl<MealMapper, Meal> implements MealService {

    @Override
    @Cacheable(value = "mealList", key = "'list'")
    public List<MealVo> getList() {
        List<Meal> list = this.baseMapper.getList();
        return getVo(list);
    }

    @Override
    @CacheEvict(value = "mealList", key = "'list'")
    public boolean del(Integer id) {
        return this.removeById(id);
    }

    @Override
    @CacheEvict(value = "mealList", key = "'list'")
    public boolean add(Meal meal) {
        return this.save(meal);
    }

    @CacheEvict(value = "mealList", key = "'list'")
    @Override
    public boolean update(Meal meal) {
        return this.updateById(meal);
    }


    private List<MealVo> getVo(List<Meal> meals) {
        List<MealVo> mealVoList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            MealVo mealVo = new MealVo();
            int finalI = i;
            mealVo.setWeekCode(finalI);
            List<MealVo.MealTypeVo> mealTypeVos = new ArrayList<>();
            List<Meal> weekList = meals.stream().filter(meal -> meal.getWeekDay() == finalI).toList();
            for (int j = 1; j <= 3; j++) {
                MealVo.MealTypeVo mealTypeVo = new MealVo.MealTypeVo();
                int finalJ = j;
                List<Meal> list = weekList.stream().filter(meal -> meal.getMealType() == finalJ).toList();
                mealTypeVo.setTypeCode(j);
                mealTypeVo.setFoods(list);
                mealTypeVos.add(mealTypeVo);
            }
            mealVo.setMealTypeVos(mealTypeVos);
            mealVoList.add(mealVo);
        }
        return mealVoList;
    }


}
